package nevo;

import java.io.*;
import java.util.*;

import nevo.core.*;
import nevo.pkgs.es.*;
import nevo.pkgs.neuro.bio.*;

public class NevoMain
{	
	public static void main(String args[])
	{	
		if (args.length < 2) {
			System.err.println("Must pass working directory and # of iterations as 1st and 2nd argument!");
			System.exit(1);
		}
		String simdir = args[0];
		System.err.println("[nevo] simulation directory='" + simdir + "'");
		
		int numiterations = Integer.parseInt(args[1]);		
		long samprate = 100000;
		
		CurrentInjectionScriptModel m = new CurrentInjectionScriptModel();
		m.setInterpreter("/bin/sh");
		m.setCommand("run-sc.sh");
		m.setWorkdir(simdir);
		m.setOutputDir(simdir);
		m.setCurrentAmplitude(50e-12);
		m.setCurrentDuration(100);
		m.setStartTime(5);
		m.setSamplingRate(samprate);		
				
		NeuronObjectiveFunction func = new NeuronObjectiveFunction();
		EvolutionaryOptimizer ev = new EvolutionaryOptimizer();
		
		DeltaMutator dmut = new DeltaMutator();
		dmut.setMaxdelta(10000);
		dmut.setMindelta(-10000);
		ev.setMutator(dmut);
		
		ev.setNumReproducingParents(10);
		ev.setNumOffspring(2);
		ev.setParentSelector(new UniformSelector());
		ev.setPopulationSelector(new ElitistSelector());
		
		int popsize = 20;
		List<Map<String,Object>> guesses = new ArrayList<Map<String,Object>>();
		for (int k = 0; k < popsize; k++) {			
			double guess = 1e3*Math.random();
			System.err.println("guess=" + guess);
         Map<String,Object> mi = new HashMap<String,Object>();
			mi.put("soma_rm", guess);
			guesses.add(mi);
		}
		
		try {		
			Double[] t2match = Utilities.fileToArray(simdir + File.separator + "vtrace_test.txt");
			func.setDataToMatch(t2match, samprate);
			
			ev.setObjectiveFunction(func);
			ev.setModel(m);			
			ev.setInitialGuesses(guesses);
			
			int numiter = Utilities.runOptimization(ev, 1e-3, numiterations);
			
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}		
		
		List<IRecord> pop = ev.getPopulation();
		for (int k = 0; k < pop.size(); k++) {
			IRecord i = pop.get(k);
         Map<String,Object> in = i.getInput();
			System.err.println(k + "\t" + in.get("soma_rm") + "\t" + i.getValue());			
		}
	}
	
	
}
